package org.example.versi.server;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author mojito
 * @Classname BootServer
 * @Description TODO
 * @Date 2020/7/20 下午9:19
 **/
@Slf4j
public class BootServer {
    private int port;
    private static volatile Executor executor;

    public BootServer(int port) {
        this.port = port;
    }

    public static Executor getExecutor() {
        if (executor == null) {
            synchronized (BootServer.class) {
                if (executor == null) {
                    executor = new ThreadPoolExecutor(4, 4,
                            10, TimeUnit.SECONDS, new LinkedBlockingQueue<>(50));
                }
            }
        }
        return executor;
    }

    public void serve(Map<String, Object> serviceMap) throws IOException {
        ServerSocket serverSocket = new ServerSocket(port);
        log.info("service published. server listen at [{}]", port);
        Executor executor = getExecutor();
        while (true) {
            Socket socket = serverSocket.accept();
            executor.execute(new RpcHandler(socket, serviceMap));
        }
    }

}
